// 全局变量
let questionnaires = {}; // 从后端获取的问卷数据
let questionnaireList = []; // 问卷列表
let currentQuestionnaire = null;
let currentQuestionnaireData = null;
let currentAnswers = {};

// 页面加载时获取问卷列表
async function loadQuestionnaires() {
    try {
        showLoading();
        const response = await fetch('/api/question_list/', {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json',
                // 如果需要认证，可以添加：
                // 'Authorization': 'Bearer ' + localStorage.getItem('token')
            }
        });

        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }

        const data = await response.json();
        questionnaireList = data.questionnaires || data;
        console.log(questionnaireList)
        renderQuestionnaireList();
        hideLoading();
    } catch (error) {
        console.error('获取问卷列表失败:', error);
        hideLoading();
        showError('获取问卷列表失败，请稍后重试');
    }
}

// 渲染问卷列表
function renderQuestionnaireList() {
    const container = document.querySelector('.questionnaire-grid');
    container.innerHTML = '';

    questionnaireList.forEach(questionnaire => {
        const card = document.createElement('div');
        card.className = 'questionnaire-card';
        card.onclick = () => startQuestionnaire(questionnaire.question_id);

        // 根据难度设置不同的样式类
        const difficultyClass = getDifficultyClass(questionnaire.difficulty);

        card.innerHTML = `
                    <span class="card-icon">${questionnaire.person}</span>
                    <h3 class="card-title">${questionnaire.question_id}</h3>
                    <p class="card-description">${questionnaire.description}</p>
                    <div class="card-meta">
                        <span class="card-duration">⏱️ 约 ${questionnaire.duration || '5-10'} 分钟</span>
                        <span class="card-difficulty ${difficultyClass}">${questionnaire.difficulty || '简单'}</span>
                    </div>
                `;

        container.appendChild(card);
    });
}

// 获取难度对应的CSS类
function getDifficultyClass(difficulty) {
    switch (difficulty) {
        case '简单':
        case 'easy':
            return 'difficulty-easy';
        case '中等':
        case 'medium':
            return 'difficulty-medium';
        case '复杂':
        case 'hard':
            return 'difficulty-hard';
        default:
            return 'difficulty-easy';
    }
}

// 获取具体问卷内容
async function loadQuestionnaireDetails(questionnaireTitle) {
    try {
        showLoading();
        window.questionnaireTitle = questionnaireTitle
        const newData = {
            title: questionnaireTitle,  // 用上文取到的title号
        };
        const response = await fetch(`/api/question_data/`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': getCookie('csrftoken'),
                // 如果需要认证，可以添加：
                // 'Authorization': 'Bearer ' + localStorage.getItem('token')
            },
            credentials: 'include',
            body: JSON.stringify(newData)
        });

        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }

        const data = await response.json();
        hideLoading();
        return data;
    } catch (error) {
        console.error('获取问卷详情失败:', error);
        hideLoading();
        showError('获取问卷详情失败，请稍后重试');
        return null;
    }
}

function goBack() {
    // 返回首页的逻辑
    window.location.href = '/';
}

async function startQuestionnaire(questionnaireTitle) {
    currentQuestionnaire = questionnaireTitle;
    currentAnswers = {};

    // 从后端获取问卷详细内容
    const questionnaireData = await loadQuestionnaireDetails(questionnaireTitle);
    if (!questionnaireData) {
        return; // 如果获取失败，不继续执行
    }
    console.log("questionnaireData", questionnaireData)
    currentQuestionnaireData = questionnaireData;
    document.getElementById('form-title').textContent = questionnaireData.title;
    document.getElementById('form-subtitle').textContent = questionnaireData.sub_description;

    // 隐藏问卷列表，显示问卷表单
    document.getElementById('questionnaire-list').style.display = 'none';
    document.getElementById('questionnaire-form').style.display = 'block';

    // 生成问题
    generateQuestions(questionnaireData.questions);

    // 滚动到顶部
    window.scrollTo(0, 0);
}

function generateQuestions(questions) {
    const container = document.getElementById('questions-container');
    container.innerHTML = '';
    questions.forEach((question, index) => {
        const questionDiv = document.createElement('div');
        questionDiv.className = 'question-item';


        const questionText = document.createElement('div');
        questionText.className = 'question-text';
        questionText.textContent = `${index + 1}. ${question.title}`;

        const optionsContainer = document.createElement('div');
        optionsContainer.className = 'options-container';

        question.options.forEach((option, optionIndex) => {
            const optionDiv = document.createElement('div');
            optionDiv.className = 'option-item';

            const radio = document.createElement('input');
            radio.type = 'radio';
            radio.name = `question_${index}`;
            radio.value = optionIndex;
            radio.onchange = () => updateAnswer(index, optionIndex);

            const label = document.createElement('label');
            label.textContent = option.text;
            // ✅ 新增：点击整项 optionDiv 触发选中并更新答案
            optionDiv.onclick = () => {
                radio.checked = true;
                updateAnswer(index, optionIndex);
            };


            optionDiv.appendChild(radio);
            optionDiv.appendChild(label);
            optionsContainer.appendChild(optionDiv);
        });

        questionDiv.appendChild(questionText);
        questionDiv.appendChild(optionsContainer);
        container.appendChild(questionDiv);
    });
}

function updateAnswer(questionIndex, answerIndex) {
    currentAnswers[questionIndex] = answerIndex;
    updateProgress();
}

function updateProgress() {
    if (!currentQuestionnaireData || !currentQuestionnaireData.questions) {
        return;
    }

    const totalQuestions = currentQuestionnaireData.questions.length;
    const answeredQuestions = Object.keys(currentAnswers).length;
    const progress = (answeredQuestions / totalQuestions) * 100;

    document.getElementById('progress-fill').style.width = `${progress}%`;
}

// 提交后返回
function goBackToList(question_id) {
    document.getElementById('questionnaire-form').style.display = 'none';
    document.getElementById('questionnaire-list').style.display = 'block';
    currentQuestionnaire = null;
    currentQuestionnaireData = null;
    currentAnswers = {};
    console.log(question_id)
    // 添加“下载报告”按钮
    const existingBtn = document.getElementById('download-report-button');
    if (!existingBtn) {
        const downloadBtn = document.createElement('button');
        downloadBtn.id = 'download-report-button';
        downloadBtn.textContent = '📄 下载报告';
        downloadBtn.style.cssText = `
            margin-top: 20px;
            margin-left: 20px;
            padding: 10px 20px;
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-size: 16px;
        `;

        downloadBtn.onclick = async () => {
            try {
                const params = new URLSearchParams({
                    question_id: question_id,
                });
                const response = await fetch(`/api/report_download/?${params}`);
                if (!response.ok) {
                    throw new Error(`下载失败：${response.status}`);
                }

                const blob = await response.blob();
                const url = window.URL.createObjectURL(blob);

                const a = document.createElement('a');
                a.href = url;
                a.download = `${window.questionnaireTitle}_报告.docx`; // 你可以根据需要设置文件名
                document.body.appendChild(a);
                a.click();
                document.body.removeChild(a);
                window.URL.revokeObjectURL(url);
            } catch (error) {
                console.error('报告下载失败:', error);
                alert('报告下载失败，请稍后重试');
            }
        };

        const container = document.getElementById('questionnaire-list');
        if (container) {
            container.parentNode.insertBefore(downloadBtn, container);
        }
    }
}

// 直接点击返回列表
function goBackToList_list() {
    document.getElementById('questionnaire-form').style.display = 'none';
    document.getElementById('questionnaire-list').style.display = 'block';
    currentQuestionnaire = null;
    currentQuestionnaireData = null;
    currentAnswers = {};
}


async function submitQuestionnaire() {
    if (!currentQuestionnaireData || !currentQuestionnaireData.questions) {
        alert('问卷数据异常，请刷新页面重试');
        return;
    }
    console.log("currentQuestionnaireData", currentQuestionnaireData)
    const totalQuestions = currentQuestionnaireData.questions.length;
    const unanswered = [];

    // 遍历所有题目，找出未答题的题号
    currentQuestionnaireData.questions.forEach((q, index) => {
        if (!currentAnswers.hasOwnProperty(q.order - 1)) {
            // index + 1 是用户看到的题号（可选）
            unanswered.push(index + 1);
        }
    });

    if (unanswered.length > 0) {
        alert(`请完成所有问题。\n您还有 ${unanswered.length} 个问题未回答：第 ${unanswered.join('、')} 题`);
        return;
    }

    // 准备提交数据
    const submissionData = {
        questionnaireName: currentQuestionnaireData.title,
        answers: currentAnswers,
        timestamp: new Date().toISOString()
    };
    console.log(submissionData)

    try {
        showLoading();
        const response = await fetch('/api/question_submit/', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': getCookie('csrftoken'),
                // 如果需要认证，可以添加：
                // 'Authorization': 'Bearer ' + localStorage.getItem('token')
            },
            body: JSON.stringify(submissionData),
            credentials: 'include',
        });

        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }

        const result = await response.json();
        hideLoading();

        alert('问卷提交成功！感谢您的参与。');
        console.log('提交结果:', result);
        goBackToList(currentQuestionnaireData.id);

    } catch (error) {
        console.error('提交问卷失败:', error);
        hideLoading();
        showError('提交失败，请稍后重试');
    }
}

// 显示加载状态
function showLoading() {
    // 可以显示一个加载遮罩层
    const loadingDiv = document.createElement('div');
    loadingDiv.id = 'loading-overlay';
    loadingDiv.style.cssText = `
                position: fixed;
                top: 0;
                left: 0;
                width: 100%;
                height: 100%;
                background: rgba(255, 255, 255, 0.8);
                display: flex;
                justify-content: center;
                align-items: center;
                z-index: 9999;
                font-size: 18px;
                color: #667eea;
            `;
    loadingDiv.innerHTML = '🔄 问卷报告分析生成中...';
    document.body.appendChild(loadingDiv);
}

// 隐藏加载状态
function hideLoading() {
    const loadingDiv = document.getElementById('loading-overlay');
    if (loadingDiv) {
        document.body.removeChild(loadingDiv);
    }
}

// 显示错误信息
function showError(message) {
    alert(message);
}

// 页面加载完成后的初始化
document.addEventListener('DOMContentLoaded', function () {
    // 页面加载时获取问卷列表
    loadQuestionnaires();
});

// 获取CSRF Token
function getCookie(name) {
    let cookieValue = null;
    if (document.cookie && document.cookie !== '') {
        const cookies = document.cookie.split(';');
        for (let i = 0; i < cookies.length; i++) {
            const cookie = cookies[i].trim();
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}
